<template>
  <div class="content-wrapper">
    <!-- <div class="content-header">权限分配</div> -->
    <div class="content-container">
      <el-form :inline="true" :model="listQuery" class="filter-container">
        <el-form-item label="类型">
          <el-select v-model="listQuery.type" class="filter-item" placeholder="请选择" size="small"  clearable>
            <el-option v-for="item in typeOptions" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-waves class="filter-item" size="small" round type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" size="small" round icon="el-icon-plus" @click="handleCreate">新增角色</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="listLoading"
        :data="list"
        highlight-current-row
        max-height="700"
      >
        <el-table-column label="编码" prop="roleCode" width="200px" />
        <el-table-column label="名称" prop="name" min-width="200px" />
        <el-table-column label="类型" prop="type" width="120px">
          <template slot-scope="{row}">
            <el-tag :type="row.type === 0 ? 'danger' : (row.type === 1 ? 'warning' : 'success')">
              {{ renderType(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px" fixed="right">
          <template slot-scope="{row,$index}">
            <el-button v-if="row.type === 1" type="text" size="mini" @click="handleUpdate(row)">
              分配权限
            </el-button>
            <el-button v-if="row.type === 2" type="text" size="mini" @click="handleUpdate(row)">
              修改
            </el-button>
            <el-button v-if="row.type === 2" type="text" size="mini" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page-number.sync="listQuery.pageNumber" :page-size.sync="listQuery.pageSize" @pagination="getList" />

      <el-drawer :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" custom-class="demo-drawer">
        <div class="demo-drawer__content">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="60px">
            <el-form-item v-if="dialogStatus==='create' ? true : false" label="编码" prop="roleCode">
              <el-input v-model.trim="temp.roleCode" />
            </el-form-item>
            <el-form-item v-if="dialogStatus==='create' ? true : (temp.type === 2 ? true : false)" label="名称" prop="name">
              <el-input v-model.trim="temp.name" />
            </el-form-item>
            <el-form-item label="权限">
              <div v-for="itemType in resourcesGroupOptions" :key="itemType.key">
                <!-- <h5 v-if="itemType.key === 1" class="info-color">菜单</h5><h5 v-else class="info-color">功能</h5> -->
                <div v-for="itemModule in itemType.value" :key="itemModule.key">
                  <i>{{ renderModuleName(itemModule.key) }}</i><br>
                  <el-checkbox v-for="item in itemModule.value" :key="item.value" v-model="selectedResourceIds" :label="item.value" @change="handleResourceChange">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </el-form-item>
          </el-form>
          <div class="demo-drawer__footer">
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              提交
            </el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { listResourceTreeItemForManage } from '@/api/uc/resource'
import { listRole, addRole, deleteRole, updateRole, listResourceId, listRoleType } from '@/api/uc/role'
import UglyMap from '@/utils/uglyMap'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNumber: 1,
        pageIndex: 0,
        pageSize: 20,
        type: undefined
      },
      typeOptions: undefined,
      temp: {
        roleCode: '',
        name: '',
        resourceIdList: []
      },
      selectedResourceIds: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      resourcesGroupOptions: undefined,
      rules: {
        roleCode: [
          { required: true, message: '角色编码不能为空', trigger: 'change' },
          { pattern: /^[a-zA-Z0-9_-]+$/, message: '角色编码由a-zA-Z0-9_-等字母组成', trigger: 'change' }
        ],
        name: [{ required: true, message: '角色名称不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.showTypeOptions()
    this.getList()
  },
  methods: {
    renderModuleName(key) {
      if (key === 'manage') {
        return '基础'
      } else if (key === 'flow') {
        return '体系'
      } else if (key === 'train') {
        return '培训'
      } else {
        return '其它'
      }
    },
    showTypeOptions() {
      listRoleType().then(response => {
        this.typeOptions = response.data
      })
    },
    getList() {
      this.listQuery.pageIndex = this.listQuery.pageNumber - 1
      this.listLoading = true
      listRole(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    renderType(type) {
      if (type === 0) {
        return '系统管理员'
      } else if (type === 1) {
        return '内置角色'
      } else {
        return '自定义'
      }
    },
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    handleResourceChange(val) {
      console.log('handleResourceChange', this.temp.resourceIdList)
      this.temp.resourceIdList = this.selectedResourceIds
    },
    resetTemp() {
      this.temp = {
        roleCode: '',
        name: '',
        resourceIdList: []
      }
      this.selectedResourceIds = []
    },
    loadResourceOptions(action) {
      listResourceTreeItemForManage({ applicationCode: 0, adminFlag: false }).then(res => {
          const data = res.data
          if(data) {
            let typeMap = new UglyMap();
            data.forEach(e => {
              let moduleMap = typeMap.computeIfAbsent(e.tag.type, (k) => new UglyMap())
              let moduleArray = moduleMap.computeIfAbsent(e.tag.module, (k) => [])
              moduleArray.push(e)
            })
            this.resourcesGroupOptions = []
            typeMap.entries().forEach(e1 => {
              let array = []
              e1.value.entries().forEach(e2 => {
                array.push({ key: e2.key, value: e2.value })
              })
              this.resourcesGroupOptions.push({ key: e1.key, value: array })
            })
            console.log(this.resourcesGroupOptions, "hihihi")
          }
          if(action) {
            action()
          }
        })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      if (this.resourcesGroupOptions === undefined) {
        this.loadResourceOptions()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addRole(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.handleFilter()
          })
        }
      })
    },
    loadDetails(row) {
      this.temp = Object.assign({}, row) 
      listResourceId({ roleId: this.temp.roleId }).then(res => {
        const data = res.data
        this.temp.resourceIdList = data
        this.selectedResourceIds = data
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (this.resourcesGroupOptions === undefined) {
        this.loadResourceOptions(() => this.loadDetails(row))
      } else {
        this.loadDetails(row)
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateRole(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.handleFilter()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole({
          roleId: row.roleId
        }).then(response => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
